﻿using System.Collections.Generic;
using UnityEngine;
namespace CommonLib.Pattern.Pool {
	public class SubPool : IObjectPool
	{
		protected Transform Container;
		protected int maxCount = 20;
		protected List<ReusableObject> objectsUsing;
		protected List<ReusableObject> objectsUnUse;
		public SubPool()
		{
			objectsUsing = new List<ReusableObject>(maxCount);
			objectsUnUse = new List<ReusableObject>(maxCount);
		}

		public SubPool(Transform transform, string name) 
		{
			Container = new GameObject(name).transform;
			Container.parent = transform;
			objectsUsing = new List<ReusableObject>(maxCount);
			objectsUnUse = new List<ReusableObject>(maxCount);
		}

		virtual public T AcquireObject<T>() where T : ReusableObject
		{
			if(objectsUnUse.Count > 0)
			{
				T @object = objectsUnUse[0] as T;
				@object?.Resume();
				objectsUnUse.Remove(@object);
				objectsUsing.Add(@object);
				return @object;
			}
			else
			{
				//超出最大容量解决方法
				//if()
				//ReusableObject @object = ReusableObject.Craete(typeof(T).ToString());
				ReusableObject @object = new UnityEngine.GameObject("temp").AddComponent(typeof(T)) as ReusableObject;
				@object.transform.SetParent(Container);
				@object?.Resume();
				objectsUsing.Add(@object);
				return @object as T;
			}
		}

		virtual public void RecycleObject(ReusableObject unUseObject)
		{
			unUseObject?.Recycle();
			unUseObject?.transform.SetParent(Container);
			if (this.objectsUsing.Contains(unUseObject))
			{
				this.objectsUsing.Remove(unUseObject);
			}
			this.objectsUnUse.Add(unUseObject);
		}
	}
}